<?php
namespace Admin\Controller;

use Admin\Model\NewsModel;
use Frame\Libs\BaseController;
use Admin\Model\TypeModel;
use Admin\Model\UserModel;

final class NewsController extends BaseController{
	public function add(){
		$this->denyAccess();
		if(IS_GET){
			$type = TypeModel::getInstance()->fetchAll();
			$this->smarty->assign("type",$type);
			$this->smarty->display("News/add.html");
		}else{
			$data = $_POST;
			if(!empty($data["content"])){
				$ModelOBJ = NewsModel::getInstance();
				$data["author_id"] = $_SESSION["id"];
				$res = $ModelOBJ->insert($data);
				if($res){
					$this->write_log("添加新闻");
					$this->ajax_return(["status"=>1,"msg"=>"添加成功","url"=>"?c=News&a=add"]);
				}else{
					$this->ajax_return(["status"=>0,"msg"=>"添加失败"]);
				}
			}else{
				$this->ajax_return(["status"=>0,"msg"=>"内容必填"]);
			}
		}
	}
	public function index(){
		$this->denyAccess();
		//搜索条件
		$where = "2>1";
		if(!empty($_REQUEST["title_search"])) $where.= "AND title LIKE '%".$_REQUEST["title_search"]."%'";

		//分页参数
		$page = isset($_GET["page"]) ? $_GET["page"] : 1;
		$pageSize = 5;
		$startPage = ($page-1)*$pageSize;
		$records = NewsModel::getInstance()->rowCount($where);
		$params = [
			"c" => CONTROLLER,
			"a" => ACTION,
		];
		//添加链接地址
		if(!empty($_REQUEST["title_search"])) $params["title_search"] = $_REQUEST["title_search"]; 
		
		//获取数据
		$news = NewsModel::getInstance()->News($where,$startPage,$pageSize);
		//创建分类对象
		$pager = new \Frame\Vendor\Pager($records, $pageSize, $page ,$params);
		$pageStr = $pager->showPage();
		
		$this->smarty->assign("pageStr",$pageStr);
		$this->smarty->assign("news",$news);
		$this->smarty->display("News/index.html");
	}
	public function dels(){
		$this->denyAccess();
		$data = $_POST;
		$res = NewsModel::getInstance()->del($data["id"]);
		if($res){
			$this->write_log("删除新闻");
			$this->ajax_return(["status"=>1,"msg"=>"删除成功"]);
		}else{
			$this->ajax_return(["status"=>0,"msg"=>"删除失败"]);
		}
	}
	public function edit(){
		$this->denyAccess();
		if(IS_GET){
			$id = $_GET["id"];
			$data = NewsModel::getInstance()->fetchOne("id=".$id);
			$type = TypeModel::getInstance()->fetchAll();
			$this->smarty->assign("type",$type);
			$this->smarty->assign("data",$data);
			$this->smarty->display("News/update.html");
		}else{
			$id = $_POST["id"];
			$title = $_POST["title"];
			$content = $_POST["content"];
			$result = NewsModel::getInstance()->edit("id='$id',title='$title',content='$content'",$id);
			if($result){
				$this->write_log("修改新闻");
				$this->jump("修改记录为{$id}的数据成功","?c=News");
			}else{
				$this->jump("修改记录为{$id}的数据成功","?c=News"); 
			}
		}
	}
}